package com.yyt.send.util;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

/**
 * apache httpClient工具类
 *
 * @author yeyangtao created at 19:31 2020/9/10
 */
public class HttpUtils {
    /**
     * post请求传输json数据
     *
     * @param url  url地址
     * @param json json数据
     * @return 结果
     */
    public static String sendPostDataByJson(String url, String json) throws ClientProtocolException, IOException {
        String result = "";

        // 创建httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        // 创建post方式请求对象
        HttpPost httpPost = new HttpPost(url);
        // 设置参数到请求对象中
        StringEntity stringEntity = new StringEntity(json, ContentType.APPLICATION_JSON);
        stringEntity.setContentEncoding("utf-8");
        httpPost.setEntity(stringEntity);
        // 执行请求操作，并拿到结果（同步阻塞）
        CloseableHttpResponse response = httpClient.execute(httpPost);

        // 获取结果实体
        // 判断网络连接状态码是否正常(0--200都数正常)
        result = EntityUtils.toString(response.getEntity(), "utf-8");
        // 释放链接
        response.close();

        return result;
    }

    public static final String URL1 = "https://user.ifeng.com/api/v1/sendsms?platform=w&systemid=1";

    public static void main(String[] args) throws IOException {
//        JSONObject object = new JSONObject();
//        object.put("applyScene",2);
//        object.put("organizationCode","123");
//        String res = sendPostDataByJson("http://192.168.1.143:8600/risk/decision/foreign/model-application/modelGet",object.toJSONString());
//        System.out.println(res);

        JSONObject object1 = new JSONObject();
        object1.put("mobile", "17779035392");
        object1.put("smsform", 1);
        String res = sendPostDataByJson(URL1, object1.toJSONString());
        System.out.println(res);
    }
}
